<!DOCTYPE HTML>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="https://lib.sinaapp.com/js/jquery/2.0.2/jquery-2.0.2.min.js"></script>
</head>
<style>
    #content{
        width: 35.1rem;
        height: 35rem;
        background-color: white;
        border:0.01rem #f4f1f1 solid;
        margin: 0 auto;
    }
    .cell{
        /*border: 0.01rem white solid;*/
        float: left;
        background-repeat:no-repeat;
        overflow: hidden;
    }
    .row{
        width: 35rem;
        margin: 0 auto;
    }
    button{
        width: 100px;
        height: 40px;
        font-size: 20px;
        background-color:#09a800;
        border-radius: 5px;
        color: white;
    }
    #easy{
        margin: 30px 2rem;
    }
    #hard{
        margin: 30px 2rem;
    }
    #harder{
        margin: 30px 2rem;
    }
    #monkey,#yang,gui{
        margin: 30px 2rem;
    }

</style>
<body>
<div class="container">
    <div class="row">
        <button id="easy">简单</button><button id="hard">中级</button><button id="harder">史诗</button>
    </div>
    <div class="row">
        <button id="monkey">羊羊羊</button><button id="yang">龟龟龟</button><button id="gui">猴猴猴</button>
    </div>
    <div class="row">
        <div id="content" class="clearfix">

        </div>
    </div>
</div>
</body>
<script>
    var level = 3;
    var width = 35;
    var child_width = width/level;

    //定义初始数组
    var arr = [0,1,2,3,4,5,6,7,8];

    var len = arr.length - 1;

    var img_url = './image/temp/yang.jpg';

    $(document).ready(function(){
        //打乱下标
        shuffle(arr);
        //生成初始图案
        createView(arr);

        //点击事件
        $("#content").on("click",".cell",function(){
            // alert($(this).data('id'));
            let obj = this
            clickImg(obj);
        });

        $("#monkey").click(function () {
            img_url = './image/temp/monkey.png';
            $(".cell").css("background-image","url('./image/temp/monkey.png')");
            $(".cell[data-id='"+len+"']").css("backgroundImage","url('')");
            $(".cell[data-id='"+len+"']").css("backgroundPosition","");
        });
        $("#yang").click(function () {
            img_url = './image/temp/yang.jpg';
            $(".cell").css("background-image","url('./image/temp/yang.jpg')");
            $(".cell[data-id='"+len+"']").css("backgroundImage","url('')");
            $(".cell[data-id='"+len+"']").css("backgroundPosition","");
        });
        $("#gui").click(function () {
            img_url = './image/temp/gui.png';
            $(".cell").css("background-image","url('./image/temp/gui.png')");
            $(".cell[data-id='"+len+"']").css("backgroundImage","url('')");
            $(".cell[data-id='"+len+"']").css("backgroundPosition","");
        });



        $("#easy").click(function () {
            level = 3;
            arr = [0,1,2,3,4,5,6,7,8];
            child_width = width/level;
            len = arr.length-1;
            shuffle(arr);
            createView(arr);
        });
        $("#hard").click(function () {
            level = 4;
            arr = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
            child_width = width/level;
            len = arr.length-1;
            shuffle(arr);
            createView(arr);
        });
        $("#harder").click(function () {
            level = 5;
            child_width = width/level;
            arr = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24];
            len = arr.length-1;
            shuffle(arr);
            createView(arr);
        });

    });


    /**
     * 打乱数组arr
     *
     * */
    function shuffle(arr) {
        let i = arr.length;
        while (i) {
            let j = Math.floor(Math.random() * i--);
            [arr[j], arr[i]] = [arr[i], arr[j]];
        }

        // 判断数组是否是有解的
        isOk(arr)
        return arr;
    }
    /**
     判断一个打乱顺序的数字拼图是否可还原
     arr: 打乱以后的数字顺序；比如[0,1,2,3,4,5,7,6,8]
     order里的数字8表示空位
     level: 3*3的拼图就传3就可以了
     返回值：arr
     */
    function isOk(arr){
        let order = [].concat(arr);
        let a;
        let count = 0;
        let m = 0;
        let n = 0;

        let len = order.length;
        for(let i=0; i<len; i++){
            a = order[i];
            if(a == level*level-1){
                m = parseInt(i/level);
                n = parseInt(i%level);
            }
            for(let j=i+1; j<len; j++){
                if(order[j]<a){
                    count++;
                }
            }
        }
        count += m;
        count += n;
        console.log(count);
        if(count%2 == 1 ){
            shuffle(arr);
        }
        return arr;
    }
    /**
     * 创建初始图案
     * */
    function createView(arr) {
        $('#content').empty()
        for (let i in arr){
            // console.log(arr[i]);
            // let sort = parseInt(i)+1;
            let str  = "<div class='cell' data-id='"+arr[i]+"' data-sort='"+i+"'></div>"
            $('#content').append(str)//在div2里面的最后面添加b2
        }
        $(".cell").width(child_width+"rem");
        $(".cell").height(child_width+"rem");
        $(".cell").css("background-image","url('"+img_url+"')");

        //循环定位图片的位置
        $(".cell").each(function(index,obj){
            let id = $(this).attr("data-id");
            let shang = Math.floor(id/level);
            let yu = Math.floor(id%level);
            if( id == len ){
                $(this).css({backgroundImage: 'url()'})
            }else{
                x = yu * child_width;
                y = shang * child_width;
                $(this).css({backgroundPosition:  "-"+x+"rem -"+y+"rem"})
                // console.log( $(this).css("backgroundPosition"));
            }
        });
    }

    function clickImg(obj){
        let id = $(obj).attr('data-id');
        if(id == len){
            //点的空白处 不处理
            return false;
        }
        // 点的不是空白处 先判断是不是在空白处的上下左右
        let flag = checkExchange(obj);
        if(!flag){
            return false;
        }

        let val = $(obj).css("backgroundPosition");
        //删除原来的
        $(obj).css("backgroundImage","url('')");
        $(obj).css("backgroundPosition","");
        //切换到新的
        $(".cell[data-id='"+len+"']").css("backgroundImage","url('"+img_url+"')");
        $(".cell[data-id='"+len+"']").css("backgroundPosition",val);
        $(".cell[data-id='"+len+"']").attr( 'data-id',id ) ;
        $(obj).attr("data-id",len);

        //验证是否过关

        setTimeout(function () {
            if(checkSuccess()){
                alert("窝草，牛批呀！")
                console.log("success");
            }else{
                console.log("fail");
            }
        },100)

    }

    function checkSuccess() {
        let flag = true;
        //循环获取图片顺序
        $(".cell").each(function(index){
            let id = $(this).attr("data-id");
            let sort = $(this).attr("data-sort");
            if(id != sort){
                flag = false
                return false;
            }
        });
        return flag;
    }
    /**
     * 检查是否可以交换图片
     * */
    function checkExchange(obj) {
        let sort = parseInt($(obj).data('sort'));
        let y = Math.floor(sort/level);
        let x = Math.floor(sort%level);

        //左移
        if( x-1 >=0 ){
            let temp_sort = sort - 1;
            let temp_id = $(".cell[data-sort='"+temp_sort+"']").attr("data-id");
            if(temp_id == len){
                return true;
            }
        }
        //右移
        if( x+1 < level ){
            let temp_sort = sort + 1;
            let temp_id = $(".cell[data-sort='"+temp_sort+"']").attr("data-id");
            if(temp_id == len){
                return true;
            }
        }
        //上移
        if( y-1 >= 0 ){
            let temp_sort = sort - level;
            let temp_id = $(".cell[data-sort='"+temp_sort+"']").attr("data-id");
            if(temp_id == len){
                return true;
            }
        }
        //下移
        if( y+1 < level ){
            let temp_sort = sort + level;
            let temp_id = $(".cell[data-sort='"+temp_sort+"']").attr("data-id");
            if(temp_id == len){
                return true;
            }
        }
        //都不满足 返回flase
        return false;
    }
</script>
</html>